package server.services;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;

import org.apache.log4j.Logger;

import server.control.Control;
import server.db.UserInteraction;
import server.jsons.GsonFactory;
import server.jsons.Message;
import server.jsons.User;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;

@Path("/auth")
public class Authentication {

	private static Logger logger = Logger.getLogger(Authentication.class
			.getName());

	@GET
	@Produces(MediaType.APPLICATION_JSON)
	public String auth(@QueryParam("email") String email,
			@QueryParam("password") String password,
			@QueryParam("type") String type,
			@QueryParam("sessionId") String sessionId,
			@Context HttpServletRequest httpRequest) {

		Control c = Control.getInstance();
		Gson json = GsonFactory.getGson();
		User u = null;

		try {
			logger.debug("Received: " + email + " and " + password);

			u = new User();
			u.setUserEmail(email);
			u.setUserPwd(password);
			u.setSessionId(sessionId);
			u.setMessage(Message.TYPE_FAIL);
			// String type = u.getMsgType();
			// u = json.fromJson(text, User.class);
			// u.setMessage(Message.TYPE_FAIL);
			if (type.equals(Message.TYPE_REGISTER_NEW_USER)) {
				if (c.registerUser(u)) {
					u.setMessage(Message.TYPE_SUCCESS);
				} else if (UserInteraction.isRegisteredUser(u.getUserEmail())) {
					u.setMessage(Message.TYPE_USER_EXISTS);
				}
			} else if (type.equals(Message.TYPE_LOGIN)) {
				if (c.loginUser(u)) {
					u.setMessage(Message.TYPE_SUCCESS);
				}
			} else if (type.equals(Message.TYPE_LOGOUT)) {
				if (c.logoutUser(u)) {
					u.setMessage(Message.TYPE_SUCCESS);
				}
			} else {
				u.setMessage(Message.TYPE_UNEXPECTED_MESSAGE);
			}

		} catch (JsonSyntaxException e) {
			logger.error("Illegal Json Format received");
			u.setMessage(Message.TYPE_INCORRECT_JSON);
			return json.toJson(u);
		}

		String callback = httpRequest.getParameter("callback");

		logger.debug(json.toJson(u));
		return json.toJson(u);

	}
}
